import * as THREE from 'three'
import { Mesh, MeshNormalMaterial } from 'three'
import createApp from '../../core'

function createTorusGeometry (dom: HTMLElement) {
  const { camera, scene, update, gui } = createApp(dom)
  camera.position.set(0, 0, 100)
  camera.lookAt(scene.position)

  const mesh = createTorusFromGeometry()
  mesh.position.x = -40
  scene.add(mesh)

  const bufferMesh = createTorusFromBufferGeometry()
  bufferMesh.position.x = 40
  scene.add(bufferMesh)

  update((time: number) => {
    const angle = time / 1000
    mesh.rotation.set(angle, angle, 0)

    bufferMesh.rotation.set(angle, angle, 0)
  })

  function updateMeshs () {
    generateGeometry(mesh)
    generateGeometry(bufferMesh)
  }

  gui.add(data, 'radius', 0, 50).onChange(updateMeshs)
  gui.add(data, 'tube', 0, 50).onChange(updateMeshs)
  gui.add(data, 'radialSegments', 1, 30, 1).onChange(updateMeshs)
  gui.add(data, 'tubularSegments', 1, 30, 1).onChange(updateMeshs)
  gui.add(data, 'arc', 0, Math.PI * 2).onChange(updateMeshs)
}

const data = {
  radius: 30,
  tube: 10,
  radialSegments: 10,
  tubularSegments: 30,
  arc: Math.PI * 2
}

function createTorusFromGeometry () {
  const { radius, tube, radialSegments, tubularSegments, arc } = data
  const geometry = new THREE.TorusGeometry(radius, tube, radialSegments, tubularSegments, arc)
  const material = new MeshNormalMaterial({ wireframe: true })
  const mesh = new Mesh(geometry, material)
  return mesh
}

function createTorusFromBufferGeometry () {
  const { radius, tube, radialSegments, tubularSegments, arc } = data
  const geometry = new THREE.TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc)
  const material = new MeshNormalMaterial({ side: THREE.DoubleSide })
  const mesh = new Mesh(geometry, material)
  return mesh
}

function generateGeometry (mesh: THREE.Mesh) {
  const { radius, tube, radialSegments, tubularSegments, arc } = data
  const geometry = new THREE.TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc)
  mesh.geometry.dispose()
  mesh.geometry = geometry
}

export {
  createTorusGeometry
}
